package com.heima.comment.utils;

import com.heima.admin.utils.common.SensitiveWordUtil;
import com.heima.aliyun.GreenTextScan;
import com.heima.common.excpetion.CustException;
import com.heima.model.comment.pojos.ApBlacklist;
import com.heima.model.common.constants.wemedia.WemediaConstants;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Set;

/**
 * 一个关于文本内容审核的工具类
 */
@Component
@Slf4j
public class ScanText {
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private GreenTextScan textScan;

    @Autowired
    private MongoTemplate mongoTemplate;

    public String scan(String content) {
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null)
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);

        //对评论内容进行审核
        Set<String> members = redisTemplate.opsForSet().members(WemediaConstants.SENSITIVE);
        //初始化敏感词Map
        SensitiveWordUtil.initMap(members);

        //调用本地敏感词库检查文本并替换文本
        long startTime = System.currentTimeMillis();
        String result = SensitiveWordUtil.getText(content);
        long endTime = System.currentTimeMillis();
        log.info("本地检查耗时:{}", endTime - startTime);

        ApBlacklist blacklist = mongoTemplate.findOne(Query.query(Criteria.where("authorId").is(user.getId())), ApBlacklist.class);

        //如果黑名单中有该用户或者本地敏感词库查出敏感词调用阿里云进一步检测
        if (blacklist != null || !result.equals(content)) {
            //创建黑名单对象并保存
            ApBlacklist apBlacklist = new ApBlacklist();
            apBlacklist.setAuthorId(user.getId());
            mongoTemplate.save(apBlacklist);

            try {
                startTime = System.currentTimeMillis();
                Map<String, String> map = textScan.greenTextScan(content);
                result = map.get("filteredContent");
                endTime = System.currentTimeMillis();
                log.info("阿里云检查耗时:{}", endTime - startTime);
            } catch (Exception e) {
                e.printStackTrace();
                log.error("调用云服务接口查询失败");
            }
        }
        return result;
    }
}
